﻿using OneRed.Draw;
using OneRed.Main.Comm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OneRed.Main.Pages;
using MahApps.Metro.Controls;
using System.Data;
using OneRed.Data;
using System.Reflection;
using System.Linq.Expressions;
using OneRed.File;

namespace OneRed.Main.Pages
{
    /// <summary>
    /// Test.xaml 的交互逻辑
    /// </summary>
    public partial class ParamsSet : Page
    {
        public ObservableCollection<Node> SelfNodes;
        public ObservableCollection<Edge> Edges;
        public static ParamsSet StatitcParamSet;
        public static string sPlitCode = ";";//分隔符
        public static string sLEN = "";//图谱参数类型：标签、边线、节点
        string sPullDataType = "";//提取数据的类型，是年或非年的量、百分比、前几位
        int iPullDataNum = 0;//提取数据类型相应的值

        ChageMapPropertis cmPro = new ChageMapPropertis();
        public ParamsSet()
        {
            InitializeComponent();
            StatitcParamSet = this;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            initMap();
            #region 最早使用继承自PAGE的自定义控制时的方法
            //var bindD = new BindDraw();
            //bindD.Nodes = SelfNodes;
            //bindD.Edges = Edges;
            //DaoHang.GetMainWindowFrame(this, bindD);
            #endregion
        }
        //绘制图形
        private async void initMap()
        {
            SelfNodes = new ObservableCollection<Node>();
            Edges = new ObservableCollection<Edge>();

            ForceDirectMap.Nodes = SelfNodes;
            ForceDirectMap.Edges = Edges;
            ForceDirectMap.Param = new Params() { Repuse = 1, Atract = 2 };
            Index.StaticIndeX.TIMap.Content = new ForceDirectMap();
            Index.StaticIndeX.TIMap.IsSelected = true;
            await Task.Run(() =>
            {
                Random rd = new Random();
                for (int i = 0; i < 10000; i++)
                {
                    Node nd = new Node();
                    nd.NodeId = Guid.NewGuid();
                    nd.Xp = rd.NextDouble() * 1000;
                    nd.Yp = rd.NextDouble() * 800;
                    nd.Text = "标签" + i;
                    SelfNodes.Add(nd);
                }

                for (int i = 0; i < 300; i++)
                {
                    Edges.Add(new Edge() { From = SelfNodes[rd.Next(0, 1000)], To = SelfNodes[rd.Next(0, 1000)], Thinck = 1, Opacity = 1, Stroke = "Red" });
                }
            });
        }
        private async void randomMap()
        {
            await Task.Run(() =>
            {
                for (int j = 0; j < 1000; j++)
                {
                    for (int i = 0; i < SelfNodes.Count; i++)
                    {
                        Random rd = new Random();
                        SelfNodes[i].Xp = rd.Next(1, 1000);
                        SelfNodes[i].Yp = rd.Next(1, 800);
                    }
                }
            });
        }
        private async void Button2_Click(object sender, RoutedEventArgs e)
        {
            await Task.Run(() =>
            {
                randomMap();
            });
        }

        #region 左侧参数设置方法
        //分析类型，默认是直接分析
        private void ChangetypeClick(object sender, SelectionChangedEventArgs e)
        {
            var CbType = sender as ComboBox;
            if (cbItemsExtractInDrect == null || cbItemsExtract == null)
                return;

            switch (CbType.SelectedIndex.ToString())
            {
                case "0"://默念值，直接分析
                    {
                        cbItemsExtractInDrect.IsEnabled = false;
                        break;
                    }
                case "1"://间接分析
                    {
                        cbItemsExtractInDrect.IsEnabled = true;
                        break;
                    }
                default:
                    {
                        cbItemsExtractInDrect.IsEnabled = false;
                        break;
                    }

            }

        }

        #endregion 左侧参数设置方法


        private void TabControl_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var basemap = e.OriginalSource as Image;
            if (basemap == null)
                return;
            switch (basemap.Name)
            {
                case "baseBar":
                    this.initMap();
                    break;
                case "baseLine":
                    randomMap();
                    break;
                case "basePie":
                    randomXp();
                    break;
                default:
                    break;
            }
        }

        private void randomXp()
        {
            var vdg = (Index.StaticIndeX.dgDataSource.Items).SourceCollection;
            Random rd = new Random();
            foreach (DataRowView v in vdg)
            {
                v.Row[3] = rd.Next(50, 60);
            }

        }

        private void PopSplite_Click(object sender, RoutedEventArgs e)
        {
            var vSplitCode = e.OriginalSource as RadioButton;
            if (vSplitCode != null)
            {
                sPlitCode = vSplitCode.Tag.ToString();

            }

        }
        #region 图谱参数设置
        //扩大边线
        private async void LargeClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(sLEN))
                return;
            switch (sLEN)
            {
                case "rbLabel":
                    await cmPro.LabelChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, false, true);
                    break;
                case "rbEdge":
                    await cmPro.EdgeChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, false, true);
                    break;
                case "rbNode":
                    await cmPro.NodeChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, false, true);
                    break;
                default:
                    break;
            }

        }
        //缩小边线
        private async void SmallClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(sLEN))
                return;
            //await cmPro.EdgeChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, false);
            switch (sLEN)
            {
                case "rbLabel":
                    await cmPro.LabelChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, false, false);
                    break;
                case "rbEdge":
                    await cmPro.EdgeChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, false, false);
                    break;
                case "rbNode":
                    await cmPro.NodeChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, false, false);
                    break;
                default:
                    break;
            }

        }
        //如果LEN的颜色发生变化
        private async void LENColor_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (string.IsNullOrEmpty(sLEN))
                return;
            switch (sLEN)
            {
                case "rbLabel":
                    await cmPro.LabelChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, true);
                    break;
                case "rbEdge":
                    await cmPro.EdgeChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, true);
                    break;
                case "rbNode":
                    await cmPro.NodeChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, true);
                    break;
                default:
                    break;
            }

        }
        //透明度
        private async void slAlpha_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (string.IsNullOrEmpty(sLEN))
                return;
            switch (sLEN)
            {
                case "rbLabel":
                    await cmPro.LabelChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, true);
                    break;
                case "rbEdge":
                    await cmPro.EdgeChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, true);
                    break;
                case "rbNode":
                    await cmPro.NodeChage(Index.StaticIndeX.TbContl.SelectedIndex, LENColor.Color, slAlpha.Value, true);
                    break;
                default:
                    break;
            }
        }

        //通过名称判断是哪个节点属性被选中
        private void MapPropertyClick(object sender, RoutedEventArgs e)
        {
            sLEN = (e.OriginalSource as RadioButton).Name;
        }
        #endregion

        //从标准源数据中提取节点基本数据
        private async void PullData(object sender, RoutedEventArgs e)
        {
            var vSYear = cbStartYear.Text;//开始年
            var vEYear = cbEndYear.Text;//结束年
            var vSlip = cbYearSplin.Text;//年分片

            List<FormatData> vSearchReuslt = null;

            if (cbHaveTime.IsOn && !string.IsNullOrEmpty(vSYear) && !string.IsNullOrEmpty(vEYear)) //如果有时间
            {
                vSearchReuslt = FormatDataCollection.Results().Where(d => Int32.Parse(d.sYear) >= Int32.Parse(vSYear) && Int32.Parse(d.sYear) <= Int32.Parse(vEYear)).ToList();
                if (vSearchReuslt.Count < 1)
                    await MainWindow.MessegeShow("提示", "选择时间区间没有数据");
            }
            else
            {
                vSearchReuslt = FormatDataCollection.Results().ToList();
            }

            if ((cbItemsExtract.SelectedItem as ComboBoxItem) == null)
            {
                await MainWindow.MessegeShow("提示", "请选择提取项");
                return;
            }
            string sTiquxiangName = (cbItemsExtract.SelectedItem as ComboBoxItem).Name;
            string sTecheng = "";
            if (tsFenxiType.IsOn)
            {
                if ((cbItemsExtractInDrect.SelectedItem as ComboBoxItem) == null)
                {
                    await MainWindow.MessegeShow("提示", "请选择特征项");
                    return;
                }
                else
                {
                    sTecheng = (cbItemsExtractInDrect.SelectedItem as ComboBoxItem).Uid;
                }
            }

            List<PushFormatData> listPubshFormatData = new List<PushFormatData>();

            //分片时间及起始时间
            MainWindow.slSpYears = FileOprate.SpliceYears(MainWindow.slYears, vSYear, vEYear, vSlip);

            string yeartemp = "";
            foreach (FormatData fd in vSearchReuslt)
            {
                if (cbHaveTime.IsOn)
                {
                    if (int.Parse(vSlip) > 1)
                    {
                        foreach (var keyyear in MainWindow.slSpYears)
                        {
                            string[] syears = keyyear.Key.Split('-');
                            if (syears.Length == 2)
                            {
                                if (int.Parse(fd.sYear) >= int.Parse(syears[0]) && int.Parse(fd.sYear) <= int.Parse(syears[1]))
                                {
                                    yeartemp = keyyear.Key;
                                    break;
                                }
                            }
                            else
                            {
                                if (fd.sYear == keyyear.Key)
                                {
                                    yeartemp = keyyear.Key;
                                    break;
                                }
                            }
                        }
                    }
                    else
                        yeartemp = fd.sYear;
                }
                else
                {
                    yeartemp = "";
                }

                listPubshFormatData.Add(new PushFormatData()
                {
                    sTiqu = fd.GetType().GetProperty(sTiquxiangName).GetValue(fd, null).ToString(),
                    sTecheng = !string.IsNullOrEmpty(sTecheng) ? fd.GetType().GetProperty(sTecheng).GetValue(fd, null).ToString() : "",
                    sYear = yeartemp
                });
            }
            //结合提取比例进行相应数量的提取
            Dictionary<string, double> dicWordsNumOrWeight = new Dictionary<string, double>();//词共现及相似性
            Dictionary<string, int> dicWordDocs = new Dictionary<string, int>();//每个字出现的文档数量
            Dictionary<string, int> dicYearWord = new Dictionary<string, int>();//年+词出现的频次

            //1.需要先算出每年度或全部词的频次及TIIDF值
            if (cbHaveTime.IsOn)
            {
                //有时间
                if (tsFenxiType.IsOn)
                {
                    //间接相似性分析
                    foreach (var vpfd in listPubshFormatData)
                    {

                    }
                }
                else
                {
                    //共现分析
                    foreach (var vpfd in listPubshFormatData)
                    {
                        //算出每一个节点相应年度的数量
                        string[] stemp = vpfd.sTiqu.Split(sPlitCode).Distinct().OrderBy(p => p).ToArray();
                        for (int i = 0; i < stemp.Length; i++)
                        {
                            string vw = stemp[i].Trim();
                            if (string.IsNullOrEmpty(vw))
                            {
                                continue;
                            }
                            //词的在文档值
                            if (!dicWordDocs.TryAdd(vw, 1))
                            {
                                dicWordDocs[vw] += 1;
                            }
                            //年+词的频次
                            string syw = vpfd.sYear + "|" + vw;
                            if (!dicYearWord.TryAdd(syw, 1))
                            {
                                dicYearWord[syw] += 1;
                            }
                            //共现值
                            for (int j = i + 1; j < stemp.Length; j++)
                            {
                                string scomword = stemp[i] + "|" + stemp[j];
                                if (!dicWordsNumOrWeight.TryAdd(scomword, 1))
                                {
                                    dicWordsNumOrWeight[scomword] += 1;
                                }
                            }
                        }
                    }
                    //将dicYearWord转换为list,方便按时间进行数量提取
                    List<YearWordNum> lsYWN = new List<YearWordNum>();
                    ///IEnumerable<YearWordNum> lsYWNResult;

                    foreach (var vywn in dicYearWord)
                    {
                        string[] syw = vywn.Key.Split('|');
                        lsYWN.Add(new YearWordNum() { Year = syw[0], Word = syw[1], Num = vywn.Value });
                    }
                    switch (sPullDataType)
                    {
                        case "rbYearNum":
                           var lsYWNResult = lsYWN.GroupBy(s => s.Year).Select(s => s.OrderByDescending(x => x.Num).Take(iPullDataNum));
                            break;
                        case "rbYearPer":
                           var lsYWNResult1 = (List<YearWordNum>)lsYWN.GroupBy(s => s.Year).Select(s => s.OrderByDescending(x => x.Num).Take(2));
                            break;
                        case "rbYearMin":
                           var lsYWNResult2 = (List<YearWordNum>)lsYWN.GroupBy(s => s.Year).Select(s => s.Where(x => x.Num > iPullDataNum));
                            break;
                        default:
                            break;
                    }

                }
            }
            else
            {
                //没有时间时，算词的总量
                if (tsFenxiType.IsOn)
                {
                    //间接相似性分析

                }
                else
                {
                    //共现分析
                }
            }
            //2.基于比例进行数据筛选


            //sPlitCode


            if (cbHaveTime.IsOn)
            {
                //有时间参数
            }
            else
            {
                //无时间参数
            }


            FormatDataCollection.addData(vSearchReuslt, true);
        }

        //获取要提取数据的类型的数量
        private void PullDataNum(object sender, HandyControl.Data.FunctionEventArgs<double> e)
        {
            var vtypenum = e.Source as HandyControl.Controls.NumericUpDown;
            if (vtypenum == null)
                return;
            iPullDataNum = int.Parse(vtypenum.Value.ToString());
            //sPullDataType = (vtypenum.Parent as RadioButton).Name;
            //iPullDataNum =int.Parse(((e.OriginalSource as RadioButton).Content as HandyControl.Controls.NumericUpDown).Value.ToString());
        }

        private void PullDataType(object sender, RoutedEventArgs e)
        {
            if (e.Source as RadioButton == null)
                return;
            sPullDataType = (e.Source as RadioButton).Name;
        }
    }
}
